package cn.edu.lingnan.Filter;

import cn.edu.lingnan.pojo.Admin;
import cn.edu.lingnan.pojo.User;
import cn.edu.lingnan.service.userservice;
import cn.edu.lingnan.service.userserviceimp;
import cn.edu.lingnan.servlet.QueryStudentAllServlet;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebFilter("/*")
public class LoginFILTER implements Filter {
    QueryStudentAllServlet userServlet=new QueryStudentAllServlet();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
          HttpServletResponse response = (HttpServletResponse) servletResponse;

        servletRequest.setCharacterEncoding("UTF-8"); //设置请求编码
        servletResponse.setCharacterEncoding("utf-8");//设置响应编码
        servletResponse.setContentType("text/html;charset=UTF-8");//设置浏览器编码

        String uri=request.getRequestURI();
          if(uri.contains("/login.jsp") || uri.contains("/l2.jsp")){
              userServlet.service(request, response);
              filterChain.doFilter(request, response);
              return;
          }
       //释放静态资源
        if(uri.contains("/images")||uri.contains("/css")/*||uri.contains("/manager")||uri.contains("/student")*/){
            filterChain.doFilter(request, response);
            return;
        }
        if(uri.contains("/login") || uri.contains("/register") || uri.contains("/studentlogin")){
            userServlet.service(request, response);
            filterChain.doFilter(request, response);
            return;
        }
        //如果创建会话,获取session对象,判断是否登录
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        User user = (User) request.getSession().getAttribute("user");
        if(user!=null || admin!=null){
            userServlet.service(request, response);
            filterChain.doFilter(request, response);
            return;
        }
        response.sendRedirect("login.jsp");
    }
    @Override
    public void destroy() {

    }
}
